#include "aky_program/aky_com_include.h"
static void aky_task_2_uart_decode(void);
static void aky_uart_2_send_byte(uint8_t data);
void clr_decode_msg(void);
uint8_t get_decode(char *decode_str);
void task2_stat_pro(void);
void time_syn_pro(void);
uint16_t get_mode_step_time(uint8_t mode_sel);

#define AKY_UART_2_BUF_MAX 500                      // 串口最大接收个数
static uint8_t aky_uart_2_buf[AKY_UART_2_BUF_MAX]; // 串口缓存
static uint16_t aky_uart_2_read_cnt = 0; // 一帧数据结束串口接收到的数据个数
static uint8_t aky_uart_2_time_out = 0;  // 超时处理  超时则将处理一帧数据标志位置1
static uint8_t flag_aky_uart_2_get_data = 0;
static uint8_t flag_aky_task_2_decode = 0; // 处理一帧数据标志位 置1代表接收到一帧数据
static uint8_t flag_notice_decode = 0; // 处理一帧数据标志位 置1代表接收到一帧数据
static uint16_t notice_decode_cnt = 0; // 一帧数据结束串口接收到的数据个数

uint8_t  SignalQ;
uint8_t IMEI[16];
uint8_t IMSI[15];
uint8_t ICCID[20];
stru_aky_task_2_t s_task_2 = {0};

cJSON *tran_time_table[5];
uint16_t i;
int64_t TrainStartTime;//训练开始时间
uint8_t TrainMode;//训练模式
int64_t TrainEndTime;//训练结束时间

void UART2_Handler(void) // uart_2 中断
{
    uint32_t chr;
    if (UART_INTStat(UART2, UART_IT_RX_THR))
    {
        while (UART_IsRXFIFOEmpty(UART2) == 0)
        {
            if (UART_ReadByte(UART2, &chr) == 0)
            {
                aky_uart_2_buf[aky_uart_2_read_cnt] = chr;
                aky_uart_2_read_cnt++;
                if (aky_uart_2_read_cnt > AKY_UART_2_BUF_MAX) // 限制最大接收个数
                {
                    aky_uart_2_read_cnt = AKY_UART_2_BUF_MAX - 1;
                }
                aky_uart_2_time_out = 0; // 超时时间清零
                flag_aky_uart_2_get_data = 1;
            }
            else
            {
                __NOP();
            }
        }
    }
    if (UART_INTStat(UART2, UART_IT_RX_TOUT))
    {
        UART_INTClr(UART2, UART_IT_RX_TOUT);
    }
}


void Timer2Callback(void) // 软件定时器 回调函数
{
    aky_uart_2_time_out++;                                        //
    if (aky_uart_2_time_out > 3 && flag_aky_uart_2_get_data == 1) // 超时着代表接收完一帧数据
    {
        aky_uart_2_time_out = 0;
        flag_aky_uart_2_get_data = 0;
        flag_aky_task_2_decode = 1; // 处理数据标志位置1
    }
}

static char *p_aky_uart_2_buf;
static void aky_task_2_uart_decode(void)
{
    uint8_t k, Checksum,cmd_code;
    uint8_t index = 0;

    if (flag_aky_task_2_decode == 1)
    {
        flag_notice_decode = 1;
        notice_decode_cnt = aky_uart_2_read_cnt;

        #if (AKY_PRINTF_TO_UART3 == 1)
        printf("rx2\n");
        for (uint16_t i = 0; i < aky_uart_2_read_cnt; i++)
        {
            printf("%c", aky_uart_2_buf[i]);
        }
        printf("\n");
        #endif
        // while (aky_uart_2_read_cnt > 1)
        // {
        //     aky_uart_2_read_cnt--;
        //     p_aky_uart_2_buf = &aky_uart_2_buf[index];
        //     index++;

        // }
        aky_uart_2_buf[aky_uart_2_read_cnt] = '\0';
        p_aky_uart_2_buf = (char *)&aky_uart_2_buf[0];
        // if(strstr(p_aky_uart_2_buf,"OK") != NULL)
        // {
        //     printf("OK\n");
        // }

        flag_aky_task_2_decode = 0;
        aky_uart_2_read_cnt = 0;
    }
    //
}

void aky_task_2(void) // 任务入口
{
    Timer2Callback();
    aky_task_2_uart_decode();
    task2_stat_pro();
    time_syn_pro();
}


 
void aky_uart_2_init(void)
{
    UART_InitStructure UART_initStruct;
    GPIO_Init(GPIOB, PIN11, 1, 0, 0, 0);
    GPIO_Init(GPIOB, PIN13, 0, 1, 0, 0);

    PORT_Init(PORTB, PIN11, PORTB_PIN11_UART2_TX, 0); // GPIOx.x配置为UART引脚
    PORT_Init(PORTB, PIN13, PORTB_PIN13_UART2_RX, 1); // GPIOx.x配置为UART引脚

    UART_initStruct.Baudrate = 115200; // 波特率
    UART_initStruct.DataBits = UART_DATA_8BIT;
    UART_initStruct.Parity = UART_PARITY_NONE;
    UART_initStruct.StopBits = UART_STOP_1BIT;
    UART_initStruct.RXThreshold = 0;
    UART_initStruct.RXThresholdIEn = 1;
    UART_initStruct.TXThreshold = 3;
    UART_initStruct.TXThresholdIEn = 0;
    UART_initStruct.TimeoutTime = 10;
    UART_initStruct.TimeoutIEn = 0;
    UART_Init(UART2, &UART_initStruct);
    UART_Open(UART2);
}


// 发送一个字节
static void aky_uart_2_send_byte(uint8_t data)
{
    uint32_t time_out = 0;
    UART_WriteByte(UART2, data);
    while (UART_IsTXBusy(UART2))
    {
        time_out++;
        __NOP();
        if (time_out > 666666)
        {
            break;
        }
    }
}

void close_4g(void)
{
    printf("close_4g\n");
    _4G_POWER_PIN_INIT;
    _4G_POWER_OFF;
    UART_Close(UART2);
    SYS->CLKEN0 &= ~(0x01 << SYS_CLKEN0_UART2_Pos);
    GPIO_Init(GPIOB, PIN11, 1, 0, 0, 0);
    GPIO_Init(GPIOB, PIN13, 1, 0, 0, 0);
    PORT_Init(PORTB, PIN11, PORTB_PIN11_GPIO, 0); // GPIOx.x配置为UART引脚
    PORT_Init(PORTB, PIN13, PORTB_PIN13_GPIO, 0); // GPIOx.x配置为UART引脚
    GPIO_ClrBit(GPIOB, PIN11);
    GPIO_ClrBit(GPIOB, PIN13);
}

void opend_4g(void)
{
    printf("opend_4g\n");
    _4G_POWER_PIN_INIT;
    _4G_POWER_ON;
    aky_uart_2_init();
}

volatile s_time_t s_time_temp;
void aky_task_2_init(void)
{

}
void aky_task_2_send_cmd(e_aky_Mcu_task2contrl cmd)
{
    if (cmd == TASK2_GET_TIME)
    {
        memset(&s_task_2, 0, sizeof(stru_aky_task_2_t));
        s_task_2.e_aky_task_2_stat = TASK_2_at;
        s_task_2.flag_send_mem = 0;
    }
    else if(cmd == TASK2_SEND_RESULT)
    {
        memset(&s_task_2, 0, sizeof(stru_aky_task_2_t));
        s_task_2.e_aky_task_2_stat = TASK_2_at;
        s_task_2.flag_send_result = 1;
    }
    else if(cmd == TASK2_SEND_MEM)
    {
        memset(&s_task_2, 0, sizeof(stru_aky_task_2_t));
        s_task_2.e_aky_task_2_stat = TASK_2_Contextid;
        s_task_2.flag_send_mem = 1;
    }
}
static void send_string(char *str)
{
    while (*str != '\0')
    {
        aky_uart_2_send_byte(*str);
        str++;
    }
}
void task2_send_string(char *str)
{
    while (*str != '\0')
    {
        aky_uart_2_send_byte(*str);
        str++;
    }
}
void task2_stat_pro(void)
{
    static uint16_t step = 0;
    static uint32_t tick_last = 0;
    static uint32_t retry_cnt = 0;
    char QHTTPPOST_Buffer[32];
    uint16_t receive_pack_len = 0;//算出总包的大小eg:”AT+QHTTPPOST=910,80,80\r\n"
    uint8_t i=0;
    static e_aky_task_2_stat_t e_aky_task_2_stat_last = TASK_2_undef; // 状态

    if (e_aky_task_2_stat_last != s_task_2.e_aky_task_2_stat)
    {
        e_aky_task_2_stat_last = s_task_2.e_aky_task_2_stat;
        step = 0;
    }

    switch (s_task_2.e_aky_task_2_stat)
    {
        case TASK_2_at:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                opend_4g();
                retry_cnt = 0;
                tick_last = g_u32_tick_cnt;
            }
            else if (step == 1)
            {
                if (g_u32_tick_cnt -  tick_last > 500 / 10)
									
                {
                    tick_last = g_u32_tick_cnt;
                    send_string("AT\r\n");
                    retry_cnt++;
                    if (retry_cnt > 10)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }
                if (get_decode("OK") == 1)
                {
                    s_task_2.e_aky_task_2_stat = TASK_2_ATE0W;
                }
            }

            break;
        }
        case TASK_2_ATE0W:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                tick_last = g_u32_tick_cnt;
                retry_cnt = 0;
            }
            else if (step == 1)
            {
                if (g_u32_tick_cnt -  tick_last > 500 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    send_string("ATE0&W\r\n");
                    retry_cnt++;
                    if (retry_cnt > 10)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }
                if (get_decode("OK") == 1)
                {
                    s_task_2.e_aky_task_2_stat = TASK_2_GSN;
                }
            }

            break;
        }
        case TASK_2_GSN:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                retry_cnt = 0;
                tick_last = g_u32_tick_cnt;
            }
            else if (step == 1)
            {
                if (g_u32_tick_cnt -  tick_last > 500 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    send_string("AT+GSN\r\n");
                    retry_cnt++;
                    if (retry_cnt > 5)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }
                if((aky_uart_2_buf[21]=='O')&&(aky_uart_2_buf[22]=='K')&&aky_uart_2_buf[2]>='0'&&aky_uart_2_buf[2]<='9') 
				{
					for(i=0;i<15;i++)
					{
						IMEI[i]=aky_uart_2_buf[i+2];
                        s_task_2.e_aky_task_2_stat = TASK_2_check_cpin;
						if(IMEI[i]<'0'||IMEI[i]>'9')
                        {
                            s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                            break;
                        }
					}
                    IMEI[15] = '\0';
				}
            }

            break;
        }

        case TASK_2_check_cpin:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                retry_cnt = 0;
                tick_last = g_u32_tick_cnt;
            }
            else if (step == 1)
            {
                if (g_u32_tick_cnt -  tick_last > 500 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    send_string("AT+CPIN?\r\n");
                    retry_cnt++;
                    if (retry_cnt > 5)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }
                if (get_decode("CPIN: READY") == 1)
                {
                    s_task_2.NOSIM = 0;
                    s_task_2.e_aky_task_2_stat = TASK_2_AT_CEREG;
                }
                if (get_decode("CME ERROR: 10") == 1)
                {
                    s_task_2.NOSIM = 1;
                }
            }

            break;
        }
        case TASK_2_AT_CEREG:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                retry_cnt = 0;
                tick_last = g_u32_tick_cnt;
            }
            else if (step == 1)
            {
                if (g_u32_tick_cnt -  tick_last > 500 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    send_string("AT+CEREG?\r\n");
                    retry_cnt++;
                    if (retry_cnt > 20)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }
                if (get_decode("CEREG: 0,1") == 1)
                {
                    s_task_2.CEREG = 1;
                    s_task_2.e_aky_task_2_stat = TASK_2_cqs;
                }
            }

            break;
        }
        case TASK_2_cqs:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                retry_cnt = 0;
                tick_last = g_u32_tick_cnt;
            }
            else if (step == 1)
            {
                if (g_u32_tick_cnt -  tick_last > 500 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    send_string("AT+CSQ\r\n");
                    retry_cnt++;
                    if (retry_cnt > 5)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }
                if (get_decode("CSQ:") == 1)
                {
                    for(i=13;i<18;i++)
                    {
                        if((aky_uart_2_buf[i] == 'O')&&(aky_uart_2_buf[i+1] == 'K'))
                        {
                            if((aky_uart_2_buf[9]<0x30)||(aky_uart_2_buf[9]>0x39))
						    {
						    	SignalQ=aky_uart_2_buf[8]-0x30;
//						    	QUA=ReceiveArray[10]-0x30;
						    }
						    else
						    {
						    	SignalQ=((aky_uart_2_buf[8]-0x30)*10+aky_uart_2_buf[9]-0x30);
//						    	QUA=ReceiveArray[11]-0x30;
						    }
                            s_task_2.e_aky_task_2_stat = TASK_2_QCCID;
                        }
                    }
                }
            }

            break;
        }
        case TASK_2_QCCID:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                retry_cnt = 0;
                tick_last = g_u32_tick_cnt;
            }
            else if (step == 1)
            {
                if (g_u32_tick_cnt -  tick_last > 500 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    send_string("AT+QCCID\r\n");
                    retry_cnt++;
                    if (retry_cnt > 5)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }
                if(aky_uart_2_buf[34]=='O'&&aky_uart_2_buf[35]=='K')
				{
					for(i=0;i<20;i++)
					{
						ICCID[i]=aky_uart_2_buf[i+10];
					}
                    s_task_2.e_aky_task_2_stat = TASK_2_CIMI;
				}
            }

            break;
        }
        case TASK_2_CIMI:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                retry_cnt = 0;
                tick_last = g_u32_tick_cnt;
           }
            else if (step == 1)
            {
                if (g_u32_tick_cnt -  tick_last > 500 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    send_string("AT+CIMI\r\n");
                    retry_cnt++;
                    if (retry_cnt > 5)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }
                if((aky_uart_2_buf[21]=='O')&&(aky_uart_2_buf[22]=='K')&&aky_uart_2_buf[2]>='0'&&aky_uart_2_buf[2]<='9') 
				{
					for(i=0;i<15;i++)
					{
						IMSI[i]=aky_uart_2_buf[i+2];
					}

                    s_task_2.e_aky_task_2_stat = TASK_2_clk;
				}
            }

            break;
        }
        case TASK_2_clk:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                retry_cnt = 0;
                tick_last = g_u32_tick_cnt;
            }
            else if (step == 1)
            {
                if (g_u32_tick_cnt -  tick_last > 500 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    send_string("AT+CCLK?\r\n");
                    retry_cnt++;
                    if (retry_cnt > 5)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }
                if (get_decode("+CCLK:") == 1)
                {
                    char *p_str_pos;
                    int day, mon, year, hour, min, sec;
                    p_str_pos = strstr((char *)aky_uart_2_buf, "+CCLK:");
                    // 使用 sscanf 解析字符串
                    if (sscanf((char *)p_str_pos, "+CCLK: \"%2d/%2d/%2d,%2d:%2d:%2d", &year, &mon, &day, &hour, &min, &sec) == 6) {
                        printf("Year: 20%d\n", year); // 假设年份是21世纪的
                        printf("Month: %d\n", mon);
                        printf("Day: %d\n", day);
                        printf("Hour: %d\n", hour);
                        printf("Minute: %d\n", min);
                        printf("sec: %d\n", sec);

                        struct tm london_tm = {0};
                        time_t london_time, beijing_time;
                        london_tm.tm_year = year;
                        london_tm.tm_mon = mon;
                        london_tm.tm_mday = day;
                        london_tm.tm_hour = hour;
                        london_tm.tm_min = min;
                        london_tm.tm_sec = sec;
                        // 调整月份和年份
                        london_tm.tm_mon -= 1; // 月份从0开始
                        london_tm.tm_year += 100; // 假设年份是21世纪的
                        london_tm.tm_isdst = -1; // 自动处理夏令时

                        // 将tm结构体转换为time_t类型
                        london_time = mktime(&london_tm);

                        // 将UTC时间转换为北京时间（UTC+8）
                        beijing_time = london_time + 8 * 3600; // 加上8小时的秒数

                        // 将北京时间转换为tm结构体
                        struct tm *beijing_tm = localtime(&beijing_time);
                        beijing_tm->tm_year += 1900;
                        beijing_tm->tm_mon += 1;
                        // 打印北京时间
                        printf("Beijing Time: %02d/%02d/%04d, %02d:%02d:%02d\n",
                               beijing_tm->tm_mday, beijing_tm->tm_mon, beijing_tm->tm_year,
                               beijing_tm->tm_hour, beijing_tm->tm_min, beijing_tm->tm_sec);


                        s_task_2.s_get_time.year = beijing_tm->tm_year - 2000; 
                        s_task_2.s_get_time.month = beijing_tm->tm_mon;
                        s_task_2.s_get_time.day = beijing_tm->tm_mday;
                        s_task_2.s_get_time.hour = beijing_tm->tm_hour;
                        s_task_2.s_get_time.min = beijing_tm->tm_min;
                        s_task_2.s_get_time.secon = beijing_tm->tm_sec;
                        if (year != 70 && year != 0)
                        {
                            s_task_2.Flag_get_time = 1;
                            if (s_task_2.flag_send_result == 1)
                            {
                                s_task_2.flag_send_result = 0;
                                s_task_2.e_aky_task_2_stat = TASK_2_Contextid;
                            }
                            else
                            {
                                s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                            }
                        }
                    } else {
                        printf("Failed to parse the date and time.\n");
                    }


                }
            }

            break;
        }
        case TASK_2_Contextid:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                retry_cnt = 0;
                tick_last = g_u32_tick_cnt;
            }
            else if (step == 1)
            {
                if (get_decode("OK") == 1)
                {
                    s_task_2.e_aky_task_2_stat = TASK_2_Contentype;
                    break;
                }
                if (g_u32_tick_cnt -  tick_last > 500 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    send_string("AT+QHTTPCFG=\"contextid\",1\r\n");
                    retry_cnt++;
                    if (retry_cnt > 5)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }
                
            }

            break;
        }
        case TASK_2_Contentype:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                retry_cnt = 0;
                tick_last = g_u32_tick_cnt;
           }
            else if (step == 1)
            {
                if (get_decode("OK") == 1)
                {
                    s_task_2.e_aky_task_2_stat = TASK_2_Requestheader;
                    break;
                }
                if (g_u32_tick_cnt -  tick_last > 500 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    send_string("AT+QHTTPCFG=\"contenttype\",4\r\n");
                    retry_cnt++;
                    if (retry_cnt > 5)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }
                
            }

            break;
        }
        case TASK_2_Requestheader:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                retry_cnt = 0;
                tick_last = g_u32_tick_cnt;
            }
            else if (step == 1)
            {
                if (get_decode("OK") == 1)
                {
                    s_task_2.e_aky_task_2_stat = TASK_2_Url_NUM;
                    break;
                }
                if (g_u32_tick_cnt -  tick_last > 500 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    send_string("AT+QHTTPCFG=\"requestheader\",1\r\n");
                    retry_cnt++;
                    if (retry_cnt > 5)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }
                
            }

            break;
        }
        case TASK_2_Url_NUM:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                retry_cnt = 0;
                tick_last = g_u32_tick_cnt;
            }
            else if (step == 1)
            {
                if (get_decode("CONNECT") == 1)
                {
                    s_task_2.e_aky_task_2_stat = TASK_2_Send_Url;
                    break;
                }
                if (g_u32_tick_cnt -  tick_last > 500 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    // send_string("AT+QHTTPURL=53,80\r\n");
                    send_string("AT+QHTTPURL=51,80\r\n");
                    retry_cnt++;
                    if (retry_cnt > 5)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }
                
            }

            break;
        }
        case TASK_2_Send_Url:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                retry_cnt = 0;
                tick_last = g_u32_tick_cnt;
            }
            else if (step == 1)
            {
                if (get_decode("OK") == 1)
                {
                    s_task_2.e_aky_task_2_stat = TASK_2_DATA_NUM;
                    break;
                }                
                if (g_u32_tick_cnt -  tick_last > 500 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    // send_string("http://device.medsunshine.com/device/v1/device/upData\r\n");
                    //正式环境 https://sczs.medsunshine.com
                    send_string("http://sczs.medsunshine.com/device/v1/device/upData\r\n");
                    retry_cnt++;
                    if (retry_cnt > 5)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }

            }

            break;
        }
        case TASK_2_DATA_NUM:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                retry_cnt = 0;
                c_json_test();
                tick_last = g_u32_tick_cnt;
            }
            else if (step == 1)
            {
                if (get_decode("CONNECT") == 1)
                {
                    // send_string(Final_pack);
                    s_task_2.e_aky_task_2_stat = TASK_2_DATA_return_OK;
                    break;
                }
                if (g_u32_tick_cnt -  tick_last > 1000 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    receive_pack_len = strlen(Final_pack);
                    sprintf(QHTTPPOST_Buffer,"AT+QHTTPPOST=%d,80,80\r\n",receive_pack_len);
                    send_string(QHTTPPOST_Buffer);
                    retry_cnt++;
                    if (retry_cnt > 5)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }
                
            }

            break;
        }
        case TASK_2_DATA_return_OK:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                retry_cnt = 0;
                send_string(Final_pack);

                tick_last = g_u32_tick_cnt;
            }
            else if (step == 1)
            {
                               
                if (get_decode("QHTTPPOST: 0,200") == 1)
                {
                    s_task_2.e_aky_task_2_stat = TASK_2_QHTTPREAD;
                    break;
                }                 
                if (g_u32_tick_cnt -  tick_last > 3000 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    retry_cnt++;
                    if (retry_cnt > 5)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }


            }

            break;
        }
        case TASK_2_QHTTPREAD:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                retry_cnt = 0;
                tick_last = g_u32_tick_cnt;

            }
            else if (step == 1)
            {
                
                if (get_decode("\"status\":0") == 1)
                {
                    s_task_2.e_aky_task_2_stat = TASK_2_get_succes;
                    break;
                }                
                if (g_u32_tick_cnt -  tick_last > 500 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    send_string("AT+QHTTPREAD=60\r\n");
                    retry_cnt++;
                    if (retry_cnt > 5)
                    {
                        retry_cnt = 0;
                        s_task_2.e_aky_task_2_stat = TASK_2_get_fail;
                    }
                }

                
            }

            break;
        }
        case TASK_2_get_succes:
        {
            if (step == 0)
            {
                step++;
                clr_decode_msg();
                tick_last = g_u32_tick_cnt;
            }
            else if (step == 1)
            {
                if (g_u32_tick_cnt -  tick_last > 5000 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    close_4g();
                    step++;
                }
            }

            break;
        }
        case TASK_2_get_fail:
        {
            if (step == 0)
            {
                step++;
                tick_last = g_u32_tick_cnt;
                clr_decode_msg();
            }
            else if (step == 1)
            {
                if (g_u32_tick_cnt -  tick_last > 5000 / 10)
                {
                    tick_last = g_u32_tick_cnt;
                    close_4g();
                    step++;
                }
            }

            break;
        }
        default:
            break;
    }
}
void clr_decode_msg(void)
{
    flag_notice_decode = 0;
    notice_decode_cnt = 0;
}
uint8_t get_decode(char *decode_str)
{
    uint8_t res = 0;
    char *p_str;
    if (flag_notice_decode == 1)
    {
        aky_uart_2_buf[notice_decode_cnt] = '\0';
        p_str = (char *)&aky_uart_2_buf[0];
        if(strstr(p_str,decode_str) != NULL)
        {
            res = 1;
        }
        clr_decode_msg();
    }
    return res;
}


void time_syn_pro(void)
{
    static uint8_t flag_syn_onece = 0;
    static uint16_t step = 0;
    static uint16_t time_cnt;
    if (flag_syn_onece == 0)
    {
        if (step == 0)
        {
            step++;

            aky_task_2_send_cmd(TASK2_GET_TIME);

            time_cnt = 0;
        }
        else if (step == 1)
        {
            if (s_task_2.Flag_get_time == 1)
            {
                g_s_time = s_task_2.s_get_time;
                printf("time syn succ\n");
                send_time_syn(g_s_time);
                flag_syn_onece = 1;
                step = 0;
            }
            // else if (s_task_2.e_aky_task_2_stat == TASK_2_get_fail)
            // {
            //     printf("time syn fail\n");
            //     flag_syn_onece = 1;
            //     step = 0;
            // }
            else
            {
                get_time();
            }
            time_cnt++;
            if (time_cnt > 8000 / 10)
            {
                time_cnt = 0;
                printf("time syn fail\n");
                flag_syn_onece = 1;
                step = 0;
            }
        }
    }
    else 
    {
        if (step == 0)
        {
            time_cnt++;
            if (time_cnt > 500 / 10)
            {
                time_cnt = 0;
                step = 1;
            }
            
        }
        else if(step == 1)
        {
            get_time();
        }
    }
}
uint32_t get_rand(void)
{
    uint32_t res = 0;
    volatile uint32_t time_out = 0;
	SYS->HRCCR |= (1 << SYS_HRCCR_ON_Pos);
	SYS->LRCCR |= (1 << SYS_LRCCR_ON_Pos);
	SYS->PRNGCR = (0 << SYS_PRNGCR_CLR_Pos) |
				  (3 << SYS_PRNGCR_MODE_Pos);
	while((SYS->PRNGCR & SYS_PRNGCR_RDY_Msk) == 0) 
    {
        __NOP();
        time_out++;
        if (time_out > 666666)
        {
            break;
        }
        
    }
	// printf("PRNGDL: %08X, PRNGDH: %08X\n", SYS->PRNGDL, SYS->PRNGDH);
    res = SYS->PRNGDL;
    return res;
}
void c_json_test(void)
{
    // 实验一数据对象
    // Datatest();
    Data_consult();
    // 创建 JSON 对象
    cJSON *DATA = cJSON_CreateObject();

    // 添加基本键值对
    cJSON_AddStringToObject(DATA, "name", s_task_2.Name);
    cJSON_AddNumberToObject(DATA, "gender", s_task_2.Gender);
    cJSON_AddNumberToObject(DATA, "age", s_task_2.Age);
    cJSON_AddStringToObject(DATA, "phoneNo", s_task_2.PhoneNo);
    cJSON_AddStringToObject(DATA, "paperNo", s_task_2.PaperNo);
    cJSON_AddNumberToObject(DATA, "trainMode", s_task_2.TrainMode);
    cJSON_AddNumberToObject(DATA, "trainPressure", s_task_2.TrainPressure);
    cJSON_AddNumberToObject(DATA, "lng", s_task_2.Lng);
    cJSON_AddNumberToObject(DATA, "lat", s_task_2.Lat);
    cJSON_AddStringToObject(DATA, "deviceAddress", s_task_2.DeviceAddress);
    cJSON_AddStringToObject(DATA, "deviceIp", s_task_2.DeviceIp);
    cJSON_AddNumberToObject(DATA, "stopFlag", s_task_2.StopFlag);

    // 创建 二级JSON 数组
    cJSON *measureData = cJSON_CreateArray();
    // 创建 二级JSON 数组下的并级对象
    if (s_task_2.flag_is_full_dat == 1)
    {
        cJSON *item_start = cJSON_CreateObject();
        cJSON_AddNumberToObject(item_start, "measureTime", s_task_2.MeasureTime_s);
        cJSON_AddNumberToObject(item_start, "leftError", s_task_2.LeftError_s);
        cJSON_AddNumberToObject(item_start, "leftSbp", s_task_2.LeftSbp_s);
        cJSON_AddNumberToObject(item_start, "leftDbp", s_task_2.LeftDbp_s);
        cJSON_AddNumberToObject(item_start, "leftPulseRate", s_task_2.LeftPulseRate_s);
        cJSON_AddNumberToObject(item_start, "rightError", s_task_2.RightError_s);
        cJSON_AddNumberToObject(item_start, "rightSbp", s_task_2.RightSbp_s);
        cJSON_AddNumberToObject(item_start, "rightDbp", s_task_2.RightDbp_s);
        cJSON_AddNumberToObject(item_start, "rightPulseRate", s_task_2.RightPulseRate_s);
        // 将二级JSON数组下的并级对象添加到二级JSON数组中
        cJSON_AddItemToArray(measureData, item_start);
    }
    
    cJSON *item_end = cJSON_CreateObject();
    cJSON_AddNumberToObject(item_end, "measureTime", s_task_2.MeasureTime);
    cJSON_AddNumberToObject(item_end, "leftError", s_task_2.LeftError);
    cJSON_AddNumberToObject(item_end, "leftSbp", s_task_2.LeftSbp);
    cJSON_AddNumberToObject(item_end, "leftDbp", s_task_2.LeftDbp);
    cJSON_AddNumberToObject(item_end, "leftPulseRate", s_task_2.LeftPulseRate);
    cJSON_AddNumberToObject(item_end, "rightError", s_task_2.RightError);
    cJSON_AddNumberToObject(item_end, "rightSbp", s_task_2.RightSbp);
    cJSON_AddNumberToObject(item_end, "rightDbp", s_task_2.RightDbp);
    cJSON_AddNumberToObject(item_end, "rightPulseRate", s_task_2.RightPulseRate);
    // 将二级JSON数组下的并级对象添加到二级JSON数组中
    cJSON_AddItemToArray(measureData, item_end);
    // 将measureData数组项添加到DATA对象中
    cJSON_AddItemToObject(DATA, "measureData", measureData);

    // 创建 二级JSON 数组
    cJSON *trainData = cJSON_CreateArray();
    // 创建 二级JSON 数组下的并级对象
    TrainMode = s_task_2.TrainMode;
    if (TrainMode == 5)
    {
        TrainMode = 4;
    }

    if (s_task_2.flag_is_full_dat == 1)
    {

        for (i = 0; i < 5; i++)
        {
            tran_time_table[i] = cJSON_CreateObject();

            
            TrainStartTime = s_task_2.TrainStartTime + (((get_mode_step_time(TrainMode) * 2) * i)  * 1000);
            TrainEndTime = TrainStartTime + (get_mode_step_time(TrainMode) * 1000);
            cJSON_AddNumberToObject(tran_time_table[i], "trainStartTime", TrainStartTime);
            cJSON_AddNumberToObject(tran_time_table[i], "trainEndTime", TrainEndTime);
            cJSON_AddNumberToObject(tran_time_table[i], "avgPressure", s_task_2.AvgPressure);
            // 将二级JSON数组下的并级对象添加到二级JSON数组中
            cJSON_AddItemToArray(trainData, tran_time_table[i]);
        }
    }
    else
    {
        int64_t time_between = 0;//中间的时长
        int64_t time_tail = 0;//
        uint16_t tran_cnt = 0;
        time_between = s_task_2.TrainEndTime - s_task_2.TrainStartTime;
        tran_cnt = time_between / ((get_mode_step_time(TrainMode) * 2) * 1000);
        time_tail = time_between % ((get_mode_step_time(TrainMode) * 2) * 1000);
        
        printf("time_tail:%lld\n", time_tail);
        if (time_tail > 1)
        {
            tran_cnt++;
        }
        
        printf("tran_cnt:%d\n", tran_cnt);
        if (tran_cnt == 0)
        {
            cJSON *duixiang2 = cJSON_CreateObject();
            if (time_between < (get_mode_step_time(TrainMode)* 1000))
            {
                cJSON_AddNumberToObject(duixiang2, "trainStartTime", s_task_2.TrainStartTime);
                cJSON_AddNumberToObject(duixiang2, "trainEndTime", s_task_2.TrainEndTime);
                cJSON_AddNumberToObject(duixiang2, "avgPressure", s_task_2.AvgPressure);
            }
            else
            {
                TrainEndTime = s_task_2.TrainStartTime + (get_mode_step_time(TrainMode) * 1000);
                cJSON_AddNumberToObject(duixiang2, "trainStartTime", s_task_2.TrainStartTime);
                cJSON_AddNumberToObject(duixiang2, "trainEndTime", TrainEndTime);
                cJSON_AddNumberToObject(duixiang2, "avgPressure", s_task_2.AvgPressure);
            }
            // 将二级JSON数组下的并级对象添加到二级JSON数组中
    
            cJSON_AddItemToArray(trainData, duixiang2);
        }
        else
        {
            for (i = 0; i < tran_cnt; i++)
            {
                tran_time_table[i] = cJSON_CreateObject();
    
                TrainStartTime = s_task_2.TrainStartTime + (((get_mode_step_time(TrainMode) * 2) * i)  * 1000);
                TrainEndTime = TrainStartTime + (get_mode_step_time(TrainMode) * 1000);
                if (TrainEndTime > s_task_2.TrainEndTime)
                {
                    //计算偏移比结束时间大, 则直接上发结束时间
                    cJSON_AddNumberToObject(tran_time_table[i], "trainStartTime", TrainStartTime);
                    cJSON_AddNumberToObject(tran_time_table[i], "trainEndTime", s_task_2.TrainEndTime);
                    cJSON_AddNumberToObject(tran_time_table[i], "avgPressure", s_task_2.AvgPressure);
                }
                else
                {
                    cJSON_AddNumberToObject(tran_time_table[i], "trainStartTime", TrainStartTime);
                    cJSON_AddNumberToObject(tran_time_table[i], "trainEndTime", TrainEndTime);
                    cJSON_AddNumberToObject(tran_time_table[i], "avgPressure", s_task_2.AvgPressure);
                }
                // 将二级JSON数组下的并级对象添加到二级JSON数组中
                cJSON_AddItemToArray(trainData, tran_time_table[i]);
            }
    
        }
    }
    // 将measureData数组项添加到DATA对象中
    cJSON_AddItemToObject(DATA, "trainData", trainData);

    //这一条其实是应该放到添加‘基本键值对’下面，不过为了迎合格式包顺序看的方便遂放此
    cJSON_AddNumberToObject(DATA, "upTime", s_task_2.UpTime);

    // 打印不带格式的 JSON 字符串
    char *lx = cJSON_PrintUnformatted(DATA);
    // 打印带格式的 JSON 字符串
    #if 22 && (AKY_DEBUG_ENABLE == 1)
    char *p_fmt_json = cJSON_Print(DATA);
    printf("%s\n", p_fmt_json);
    printf("Unformatte \n%s\n", lx);

    #endif

    //传参给AES数据加密
    aky_test_aes(lx);

    // 释放内存
    cJSON_Delete(DATA);
    // free(lx);

    //上述步骤已经把加密后的数据放在了Base64recive数组里面了，由于需要重新组包一个数组，所以最后在数据外层定义了一个JSON对象
    // 创建 JSON 对象
    cJSON *UPdata = cJSON_CreateObject();
    // printf("before Base64recive =\n%s\n", Base64recive);

    cJSON_AddStringToObject(UPdata, "requestData", Base64recive);
    char *Packet = cJSON_PrintUnformatted(UPdata);
    // printf("Packet =\n%s\n", Packet);
    strcpy(Base64recive,Packet);
    // printf("strcpy Base64recive =\n%s\n", Base64recive);
    // 释放内存
    cJSON_Delete(UPdata);
    // free(Packet);
    
    char Mid_buffer[512];
    char rand_buf[128];
    //以下是数据前面头的组包过程
    sprintf(Final_pack,"POST /device/v1/device/upData HTTP/1.1\r\n");
    // sprintf(Mid_buffer,"Host: device.medsunshine.com\r\n");
    sprintf(Mid_buffer,"Host: sczs.medsunshine.com\r\n");
    strcat(Final_pack,Mid_buffer);
    sprintf(rand_buf,"%08x",(uint32_t)get_rand());
    sprintf(Mid_buffer,"nonce: %s-cb9e-6e5f-1bc6-2057%08x\r\n",rand_buf,(uint32_t)timetostamp(g_s_mem_send.s_time));
    strcat(Final_pack,Mid_buffer);
    sprintf(Mid_buffer,"timestamp: %lld\r\n",timetostamp(g_s_mem_send.s_time));
    strcat(Final_pack,Mid_buffer);
    sprintf(Mid_buffer,"deviceId: %s\r\n",DEVICE_ID);
    strcat(Final_pack,Mid_buffer);
    sprintf(Mid_buffer,"deviceType: %s\r\n",DEVICE_TYPE);
    strcat(Final_pack,Mid_buffer);
    sprintf(Mid_buffer,"signature: %s\r\n",Encrypted_Header(rand_buf));
    strcat(Final_pack,Mid_buffer);
    sprintf(Mid_buffer,"Content-Type: application/json\r\n");
    strcat(Final_pack,Mid_buffer);
    sprintf(Mid_buffer,"Content-Length: %d\r\n\r\n",strlen(Base64recive));
    strcat(Final_pack,Mid_buffer);
    //连接数据前面头的组包和数据包后组成的最终上传大包
    strcat(Final_pack,Base64recive);
    sprintf(Mid_buffer,"\r\n");
    strcat(Final_pack,Mid_buffer);
    #if 00
    printf("%s\n", Final_pack);

    #endif

    // int nnnn=Encrypted_Header();
    

}

// void Datatest(void) 
// {
//     s_task_2.Name = "lxxxxxx";
//     s_task_2.Gender = 1;
//     s_task_2.Age = 26;
//     s_task_2.PhoneNo = "12345678901";
//     s_task_2.PaperNo = "112233445566778899";
//     s_task_2.TrainMode = 1;
//     s_task_2.TrainPressure = 200;
//     s_task_2.Lng = 60;
//     s_task_2.Lat = 70;
//     s_task_2.DeviceAddress = "AKY";
//     s_task_2.DeviceIp = "70.99.82.28";
//     s_task_2.StopFlag = 0;
//     s_task_2.MeasureTime = 1734340887829;
//     s_task_2.LeftError = 0;
//     s_task_2.LeftSbp = 120;
//     s_task_2.LeftDbp = 80;
//     s_task_2.LeftPulseRate = 60;
//     s_task_2.RightError = 0;
//     s_task_2.RightSbp = 120;
//     s_task_2.RightDbp = 80;
//     s_task_2.RightPulseRate = 60;
//     s_task_2.TrainStartTime = 1734340887829;
//     s_task_2.TrainEndTime = 1734340887829;
//     s_task_2.AvgPressure = 154;
//     s_task_2.TrainError = 0;
//     s_task_2.UpTime = 1734340887829;
// }

void Data_consult(void) 
{
    s_task_2.Name = (char *)g_s_mem_index.user_name_buf;
    if (g_s_mem_index.gender == MAN)
    {
        s_task_2.Gender = 1;
    }
    else
    {
        s_task_2.Gender = 0;
    }
    int temp;
    sscanf((char *)g_s_mem_index.age_buf,"%d",&temp);
    s_task_2.Age = temp;

    s_task_2.PhoneNo = (char *)g_s_mem_index.phone_num_buf;
    s_task_2.PaperNo = "112233445566778899";
    s_task_2.TrainMode = g_s_mem_send.TrainMode;
    s_task_2.TrainPressure = g_s_mem_send.TrainPressure;
    s_task_2.Lng = 60;
    s_task_2.Lat = 70;
    s_task_2.DeviceAddress = "AKY";
    s_task_2.DeviceIp = "70.99.82.28";
    s_task_2.StopFlag = 0;


    s_task_2.MeasureTime = timetostamp(g_s_mem_send.s_time);
    s_task_2.LeftError = 0;
    s_task_2.LeftSbp = g_s_mem_send.s_left_bp.sys;
    s_task_2.LeftDbp = g_s_mem_send.s_left_bp.dia;
    s_task_2.LeftPulseRate = g_s_mem_send.s_left_bp.pul;
    s_task_2.RightError = 0;
    s_task_2.RightSbp = g_s_mem_send.s_right_bp.sys;
    s_task_2.RightDbp = g_s_mem_send.s_right_bp.dia;
    s_task_2.RightPulseRate = g_s_mem_send.s_right_bp.pul;
    s_task_2.AvgPressure = s_task_2.TrainPressure;
    s_task_2.TrainError = 0;
    s_task_2.UpTime = timetostamp(g_s_time);

    if (g_s_mem_send.flag_ful_dat == 1)
    {
        s_task_2.TrainStartTime = (timetostamp(g_s_mem_send.s_time) - (((60 * g_s_mem_send.s_train_time.min) + (g_s_mem_send.s_train_time.secon)) * 1000));
        s_task_2.TrainEndTime = timetostamp(g_s_mem_send.s_time);
    
        s_task_2.flag_is_full_dat = 1;
        s_task_2.MeasureTime_s = s_task_2.TrainStartTime;
        s_task_2.LeftError_s = 0;
        s_task_2.LeftSbp_s = g_s_mem_send.s_left_bp_start.sys;
        s_task_2.LeftDbp_s = g_s_mem_send.s_left_bp_start.dia;
        s_task_2.LeftPulseRate_s = g_s_mem_send.s_left_bp_start.pul;
        s_task_2.RightError_s = 0;
        s_task_2.RightSbp_s = g_s_mem_send.s_right_bp_start.sys;
        s_task_2.RightDbp_s = g_s_mem_send.s_right_bp_start.dia;
        s_task_2.RightPulseRate_s = g_s_mem_send.s_right_bp_start.pul;
    
    }
    else
    {
        s_task_2.flag_is_full_dat = 0;
        s_task_2.TrainStartTime = timetostamp(g_s_mem_send.s_time);
        s_task_2.TrainEndTime = (timetostamp(g_s_mem_send.s_time) + (((60 * g_s_mem_send.s_train_time.min) + (g_s_mem_send.s_train_time.secon)) * 1000));

    }
}

//时间转时间戳函数
int64_t timetostamp(s_time_t time)
{
    struct tm tm;
	volatile time_t timestamp;
    int day, mon, year, hour, min, sec;
	int64_t temp;

    // 初始化 tm 结构
	memset(&tm, 0, sizeof(struct tm));

	// 解析日期时间字符串
	//if (strptime(date_str, "%Y-%m-%d %H:%M:%S", &tm) == NULL) {
	//	fprintf(stderr, "Failed to parse date string\n");
	//	return 1;
	//}
    year=time.year;
    mon=time.month;
    day=time.day;
    hour=time.hour;
    min=time.min;
    sec=time.secon;
	// sscanf((char *)date_str, "20%2d-%2d-%2d %2d:%2d:%2d", &year, &mon, &day, &hour, &min, &sec);
	// printf("Year: 20%d\n", year); // 假设年份是21世纪的
	// printf("Month: %d\n", mon);
	// printf("Day: %d\n", day);
	// printf("Hour: %d\n", hour);
	// printf("Minute: %d\n", min);
	// printf("sec: %d\n", sec);
	tm.tm_year = year;
	tm.tm_mon = mon;
	tm.tm_mday = day;
	tm.tm_hour = hour;
	tm.tm_min = min;
	tm.tm_sec = sec;
	// 调整月份和年份
	tm.tm_mon -= 1; // 月份从0开始
	tm.tm_year += 100; // 假设年份是21世纪的
	tm.tm_isdst = -1; // 自动处理夏令时
	// 将 tm 结构转换为UTC时间戳
	//timestamp = timegm(&tm);
	// 将tm结构体转换为time_t类型
	timestamp = mktime(&tm);

	// 将UTC时间转换为北京时间（UTC+8）
	timestamp = timestamp - 8 * 3600; // 加上8小时的秒数
	temp = timestamp;
	temp*=1000;
	if (temp == -1) {
		printf("Failed to convert to timestamp\n");
	}

	// printf("UTC Timestamp: %lld\n", temp);
    return  temp;
}

s_time_t timestamp_to_s_time(int64_t timestamp)
{
    struct tm *timeinfo;
    s_time_t s_time;

    timestamp /= 1000;
	timestamp = timestamp + 8 * 3600; // 加上8小时的秒数

    // 将时间戳转换为本地时间
    timeinfo = localtime((time_t *)&timestamp);

    // 填充s_time_t结构体
    s_time.year = timeinfo->tm_year - 100; // tm_year是从1900年开始的年份，我们需要减去100得到21世纪的年份
    s_time.month = timeinfo->tm_mon + 1;    // tm_mon是从0开始的月份，我们需要加1
    s_time.day = timeinfo->tm_mday;
    s_time.hour = timeinfo->tm_hour;
    s_time.min = timeinfo->tm_min;
    s_time.secon = timeinfo->tm_sec;

    return s_time;
}


uint8_t get_csq_val(void)
{
    return SignalQ;
}


void send_4g_test_cmd(void)
{
    clr_decode_msg();
    opend_4g();
    aky_block_delay_ms(50);
    send_string("AT\r\n");
}
uint8_t get_4g_test_ok_flag(void)
{
    if (get_decode("OK") == 1)
    {
        return  1;
    }
			return  0;

}
